package core

import (
	"fmt"
	"io"

	"github.com/quic-go/quic-go"
)

// ========================================
// 协议相关函数
// ========================================

// NewErrorMessage 创建错误消息
func NewErrorMessage(tunnelID, requestID string, errorCode int, errorMsg string) *TunnelMessage {
	errorBody := fmt.Sprintf(`{"error_code":%d,"error_message":"%s"}`, errorCode, errorMsg)
	return &TunnelMessage{
		Version:      ProtocolVersion,
		MessageType:  MessageTypeError,
		ProtocolType: ProtocolHTTP,
		TunnelID:     tunnelID,
		RequestID:    requestID,
		ConnectionID: "",
		Body:         []byte(errorBody),
		BodyLength:   uint64(len(errorBody)),
	}
}

// NewChunkMessage 创建分块消息
func NewChunkMessage(tunnelID, requestID string, chunkID uint64, isLast bool, data []byte) *ChunkMessage {
	return &ChunkMessage{
		TunnelID:  tunnelID,
		RequestID: requestID,
		ChunkID:   chunkID,
		IsLast:    isLast,
		Data:      data,
	}
}

// Write 写入消息到stream
// 注意：实际实现在main包的quic_protocol.go中
// 这里提供接口，由main包注入实现
var WriteMessage func(stream quic.Stream, msg *TunnelMessage) error

// ReadMessage 从stream读取消息
// 注意：实际实现在main包的quic_protocol.go中
// 这里提供接口，由main包注入实现
var ReadMessage func(r io.Reader) (*TunnelMessage, error)

// Write TunnelMessage的Write方法
func (m *TunnelMessage) Write(stream quic.Stream) error {
	if WriteMessage == nil {
		return fmt.Errorf("WriteMessage function not initialized")
	}
	return WriteMessage(stream, m)
}

// WriteChunkMessage 写入分片消息到stream
// 注意：这是一个独立的函数，不走TunnelMessage序列化
var WriteChunkMessage func(w io.Writer, chunk *ChunkMessage) error
